package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.config.Configuration;
import com.conversationboard.controller.debug.ServletDebugInfo;
import com.conversationboard.logger.Logger;
import com.conversationboard.model.User;
import com.conversationboard.model.preferences.UserPreferences;
import com.conversationboard.security.EncryptedKey;
import com.conversationboard.security.EncryptionException;

@WebServlet(name = "AdminToggleAdminMenuControllerServlet", urlPatterns = "/Admin/AdminToggleAdminMenuControllerServlet")
public class AdminToggleAdminMenuControllerServlet extends HttpServlet {

	private static final long serialVersionUID = 7630610370439302654L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		try {

			User user = User.get(request.getUserPrincipal().getName());

			if (!user.isAdmin()) {
				return;
			}

			String key = request.getParameter("key");
			EncryptedKey encryptedKey = new EncryptedKey();

			if (!encryptedKey.isValid(key, user.getLoginId())) {
				Logger.log(new Date(), "Part 1 of error: " + this.getClass().getName(), user);
				String postRequest = ServletDebugInfo.getRawRequest(request);
				Logger.log(new Date(), "Part 2 of error:\n\n" + postRequest, user);
				return;
			}

			UserPreferences preferences = user.getPreferences();

			preferences.setHideAdminMenu(!preferences.isHideAdminMenu());
			preferences.store();

			response.sendRedirect(Configuration.getInstance().getRoot() + "/index.jsp");

		} catch (EncryptionException e) {
			throw new ServletException(e);
		} catch (SQLException e) {
			throw new ServletException(e);
		}

	}

}
